from .db_model import db
from .db_model import User, Auth


class user_control():
    
    def find_user(self, user_info):
        get_user = User.query.filter_by(user_name=user_info['user_name']).first()
        return get_user

    def add_user(self, user_info):
        new_user = User()
        new_user.user_name = user_info['user_name']
        new_user.password = user_info['password']
        new_user.user_level = user_info['user_level']
        db.session.add(new_user)
        db.session.commit()
        db.session.close()
        return True
    
    def update_user(self, user_info):
        User.query.filter_by(user_name=user_info['user_name'])\
                            .update(user_info['update_info'])
        db.session.commit()
        db.session.close()
        return True
    
    def delete_user(self, user_info):
        del_user = User.query.filter_by(user_name=user_info['user_name']).first()
        db.session.delete(del_user)
        db.session.commit()
        db.session.close()
        return True
    
class get_auth():
    
    def add_auths(self, auth_info):
        auth = Auth.query.filter_by(user_name=auth_info['user_name']).first()
        if not auth:
            auth = Auth()
            auth.user_name = auth_info['user_name']
            auth.user_id = User.query.filter_by(user_name=auth_info['user_name']).first().user_id
            auth.login_time = auth_info['login_time']
            auth.login_statu = auth_info['login_statu']

            db.session.add(auth)
        else:
            Auth.query.filter_by(user_name=auth_info['user_name'])\
                            .update({"login_time":auth_info['login_time'],
                                     "login_statu":auth_info['login_statu']})
        db.session.commit()
        db.session.close()
        return True
    
    def get_auths(self, auth_info):
        auth = Auth.query.filter_by(login_statu=auth_info['login_statu']).first()
        # db.session.commit()
        # db.session.close()
        return auth
    
    def find_auths(self, auth_info):
        auth = Auth.query.filter_by(user_name=auth_info['user_name']).first()
        # db.session.commit()
        # db.session.close()
        return auth

    def set_auths(self, auth_info):
        Auth.query.filter_by(login_statu=auth_info['login_statu'])\
                            .update(auth_info['update_info'])
        # db.session.commit()
        # db.session.close()

    def del_auths(self, auth_info):
        del_auth = Auth.query.filter_by(login_statu=auth_info['login_statu']).first()
        if del_auth is None:
            return True
        db.session.delete(del_auth)
        db.session.commit()
        db.session.close()
